package com.cqhfan.contentservice.mq;

import com.cqhfan.contentservice.service.CommentService;
import com.cqhfan.contentservice.service.WorksService;
import com.cqhfan.core.constans.MqConstants;
import com.cqhfan.pojo.content.po.Comment;
import com.cqhfan.pojo.content.po.Works;
import com.cqhfan.pojo.interaction.dto.LikedChangeDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 眭传洪
 * @create 2025-08-14 18:00
 */
@Slf4j
@Component
public class LikedChangeListener {

    @Resource
    private WorksService worksService;

    @Resource
    private CommentService commentService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.QUEUE.WORKS_LIKED_CHANGE_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.EXCHANGE.LIKED_TOPIC_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.KEY.WORKS_LIKED_CHANGE_KEY
    ))
    public void handleWorksLikedChange(List<LikedChangeDTO> list) {
        log.info("收到作品点赞数变更的消息，变更数据：{}", list);
        // 构建修改列表
        List<Works> listWorks = list.stream().map(item -> {
            Works works = new Works();
            works.setId(item.getBizId());
            works.setLikeQuantity(item.getQuantity().intValue());
            return works;
        }).toList();

        // 更新数据库
        worksService.updateBatchById(listWorks);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.QUEUE.WORKS_COMMENT_LIKED_CHANGE_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqConstants.EXCHANGE.LIKED_TOPIC_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.KEY.WORKS_COMMENT_LIKED_CHANGE_KEY
    ))
    public void handleWorksCommentLikedChange(List<LikedChangeDTO> list) {
        log.info("收到作品评论点赞数变更的消息，变更数据：{}", list);
        // 构建修改列表
        List<Comment> listComments = list.stream().map(item -> {
            Comment comment = new Comment();
            comment.setId(item.getBizId());
            comment.setLikesQuantity(item.getQuantity().intValue());
            return comment;
        }).toList();

        // 更新数据库
        commentService.updateBatchById(listComments);
    }

}
